package com.ow.framework.data.handler.config;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.ow.framework.common.Constant;
import com.ow.framework.data.dao.SessionFactory;
import com.ow.framework.data.handler.IHandlerCriteria;
import com.ow.framework.exception.DetailException;


public class SqlSessionConfig implements IHandlerCriteria
{
	private String fileName;
	static Logger log = Logger.getLogger(Constant.FRAMEWORK);
	private static ArrayList<String> dataSource = new ArrayList<String>();	
	/**
	 * 数据库初始化  
	 */
	public SqlSessionConfig(String fileName)
	{
		this.fileName = fileName;
	}

	public void appInit() {
		Reader reader = null;
		try {
			SAXBuilder sax =new SAXBuilder();
			sax.setValidation(false);
			sax.setEntityResolver(new EntityResolver() {
                public InputSource resolveEntity(String publicId,
                        String systemId) throws SAXException, IOException {
                    return new InputSource(new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes()));
                }
            });			
			Document doc = sax.build(Resources.getResourceAsStream(fileName));
			Element environments = doc.getRootElement().getChild("environments");
			List<Element> list = environments.getChildren();
			for(int i =0 ; i<list.size();i++){
				Element etmp = (Element) list.get(i);
				String str = etmp.getAttribute("id")==null?"":etmp.getAttribute("id").getValue();
				if(str != null && !"".equals(str)){
					boolean ismap = false;
					int idx = str.indexOf("_");
					if (idx > -1){						
						String dstype = str.substring(0,idx);
						for (int j=0; j<Constant.DATASOURCE_TYPE.length; j++){
							if (dstype.equals(Constant.DATASOURCE_TYPE[j])){
								ismap = true;
								break;
							}
						}
						if (!ismap){
							throw new Exception("ibatis.config.xml 配置文件:environment id 属性格式错误.");
						}
						else{
							dataSource.add(str);
						}
					}
					else{
						throw new Exception("ibatis.config.xml 配置文件:environment id 属性格式错误.");
					}
				}
			}
			SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
			for(int i =0 ;i<dataSource.size();i++){
				System.out.println("系统" + dataSource.get(i)+ "数据源DAO对象正在加载中，请稍后.....");
				reader = Resources.getResourceAsReader(fileName);
				SqlSessionFactory sf = sfb.build(reader,dataSource.get(i));
				if(sf!=null){
					SessionFactory.getInstance().getSqlSessionFactoryMap().put(dataSource.get(i), sf);
					System.out.println("系统" + dataSource.get(i) + "数据源DAO对象加载成功！");
				}else{
					System.out.println("系统" + dataSource.get(i) + "数据源DAO对象加载失败！");
				}
			}
		} catch (Exception e) {
			String error = DetailException.expDetail(e,  PermissionConfig.class);
			log.error(error);
			System.exit(-2);
		}
	}
	
}
